import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { Observable } from 'rxjs';
import { XjwtService } from 'src/xjwt/xjwt.service';

@Injectable()
export class LoginGuard implements CanActivate {
  constructor(private configService:ConfigService, private xjwtService:XjwtService){}
  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    let request = context.switchToHttp().getRequest();
    const white = this.configService.get<any[]>('white')
    const route = request.route
    let path:string = route.path
    const routePrefix = this.configService.get('routePrefix')
    if(routePrefix) {
      path = path.substr(routePrefix.length + 1)
    }

    const token = request.headers.authorization
    const isRequiredLogin = white.includes(path) == false //是否要求登录
    const loginJwt = this.configService.get('jwt.login')
    
    if(isRequiredLogin && !token) { //需要登录
      return false
    }


    if(token) {
      let result = this.xjwtService.verify(token, {secret : loginJwt.secret})
      if(isRequiredLogin && result === null) {
        return false        
      }

      if(result) {
        const userId = (result.key - loginJwt.scale) / loginJwt.scale
        request.user = {
          userId : userId
        }
        request.userId = userId
      }

    }


    request.clientSource = request.headers['client-source']


    return true;
  }

}
